package com.moyun.zbmy.zizhou.ui.activities;

import android.os.Bundle;
import android.os.Handler;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.ArrayMap;
import android.util.Pair;
import android.view.View;
import android.widget.Toast;

import com.canyinghao.canrefresh.CanRefreshLayout;
import com.google.gson.Gson;
import com.jiongbull.jlog.JLog;
import com.moyun.zbmy.zizhou.R;
import com.moyun.zbmy.zizhou.application.Constances;
import com.moyun.zbmy.zizhou.base.BaseActivity;
import com.moyun.zbmy.zizhou.beans.FocusColumn;
import com.moyun.zbmy.zizhou.beans.HomeListItem;
import com.moyun.zbmy.zizhou.beans.HomeLive;
import com.moyun.zbmy.zizhou.beans.LiveItem;
import com.moyun.zbmy.zizhou.beans.NewsClickCountBean;
import com.moyun.zbmy.zizhou.beans.NewsIdBean;
import com.moyun.zbmy.zizhou.beans.NewsItem;
import com.moyun.zbmy.zizhou.beans.NewsListClickRequestBean;
import com.moyun.zbmy.zizhou.beans.NewsListClickVo;
import com.moyun.zbmy.zizhou.beans.SingleResult;
import com.moyun.zbmy.zizhou.http.AbsListNetCallback;
import com.moyun.zbmy.zizhou.http.AbsNetCallBack;
import com.moyun.zbmy.zizhou.http.NetUtils;
import com.moyun.zbmy.zizhou.ui.adapter.NewListAdapter;
import com.moyun.zbmy.zizhou.ui.adapter.holder.HomeLiveHolder;
import com.moyun.zbmy.zizhou.ui.util.IListShowData;
import com.moyun.zbmy.zizhou.ui.utils.TitleUtils;
import com.moyun.zbmy.zizhou.utils.ListTypeUtils;
import com.ruihang.generalibrary.utils.ListUtils;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import okhttp3.MediaType;
import okhttp3.RequestBody;

/**
 * 书记专区、县长专区 （通用 banner+新闻列表模板）
 */
public class CommonCultureActivity extends BaseActivity implements CanRefreshLayout.OnRefreshListener
        , CanRefreshLayout.OnLoadMoreListener{

    @BindView(R.id.common_refresh)
    protected CanRefreshLayout refreshLayout;
    @BindView(R.id.can_content_view)
    protected RecyclerView recyclerView;
    private NewListAdapter adapter;

    private String bannerUrlTemp, newsUrlTemp, liveUrlTemp, popularUrlTemp, specialAreaUrlTemp;

    private List<IListShowData> newsList = new ArrayList<>();
    private boolean isReset;

    private Handler handler;
    private boolean isRefresh = false;
    private int newsIndex = 0;
    private int newsPageAll = 1;

    private String title;
    private String channelUrl;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        title = getIntent().getStringExtra(EX_TITLE);
        new TitleUtils(this).setBackVisible(true).useAndSetTxTitle(title);
        channelUrl = getIntent().getStringExtra(EX_URL);
        handler = new Handler();
        initViews();
    }

    @Override
    protected void initInject() {
        setContentView(R.layout.activity_common_culture);
        ButterKnife.bind(this);
    }


    @Override
    public void onLoadMore() {
        if (newsIndex < newsPageAll - 1) {
            if (!getNewsList(NewListAdapter.VIEWTYPE_NEWS, newsIndex + 1)) {
//                dataAddHelper.removeUpItem(NewListAdapter.VIEWTYPE_NEWS);
                Toast.makeText(this, "获取更多失败", Toast.LENGTH_LONG).show();
            }
        }
    }

    @Override
    public void onRefresh() {
        isRefresh = true;
        newsList.clear();
        //首次加载数据，或之后下拉刷新
        getChannelList();
    }


    private void initViews() {
        LinearLayoutManager layoutManager = new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false);
        recyclerView.setLayoutManager(layoutManager);
        recyclerView.setItemAnimator(new DefaultItemAnimator());
        refreshLayout.setOnRefreshListener(this);
        refreshLayout.setOnLoadMoreListener(this);
        refreshLayout.setLoadMoreEnabled(false);
        refreshLayout.autoRefresh();

        recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {

            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
            }

            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                LinearLayoutManager layoutManager = (LinearLayoutManager) recyclerView.getLayoutManager();
                int topPosition = layoutManager.findFirstVisibleItemPosition();
                RecyclerView.LayoutManager manager = recyclerView.getLayoutManager();
                View topView = layoutManager.findViewByPosition(topPosition);
                if (null != topView && recyclerView.getChildViewHolder(topView) instanceof HomeLiveHolder) {
                    int bottom = topView.getBottom();
                    int height = topView.getHeight();
                    if (dy > 0) {
                        if (bottom < height / 10) {
                            HomeLiveHolder liveHolder = (HomeLiveHolder) recyclerView.getChildViewHolder(topView);
                            liveHolder.onIPause();
                            liveHolder.setLiveMute(liveHolder.isMute());

                        }
                    } else if (dy < 0) {
                        if (bottom > height / 10) {
                            HomeLiveHolder liveHolder = (HomeLiveHolder) recyclerView.getChildViewHolder(topView);
                            if (!liveHolder.isResuming()) {
                                liveHolder.onIResume();
                                liveHolder.setLiveMute(liveHolder.isMute());
                            }
                        }
                    }
                }
            }
        });


    }


    /**
     * 获取精选模块 多个类型的显示数据。
     */
    private void getChannelList() {
        if (TextUtils.isEmpty(channelUrl)) {
            toast("数据错误");
            JLog.e("int " + this.getClass().getSimpleName() + " url wrong ::" + channelUrl);
            refreshLayout.refreshComplete();
            return;
        }
        NetUtils.getNetAdapter().getChannelArray(getOwnerName(), channelUrl, new AbsListNetCallback<FocusColumn>(ListTypeUtils.FocusColums()) {
            @Override
            public void onSuc(List<FocusColumn> focusColumns) {
                if (ListUtils.isListValued(focusColumns)) {
                    resetUrlTemps();
                    for (FocusColumn fc : focusColumns) {
                        if (fc != null) {
                            switch (fc.getSubChannelType()) {
                                case NewListAdapter.VIEWTYPE_BANNER:
                                    bannerUrlTemp = fc.getChannelUrl();
                                    break;
//                                case NewListAdapter.VIEWTYPE_EXPRESS:
//                                    expressUrlTemp = fc.getChannelUrl();
//                                    break;
                                case NewListAdapter.VIEWTYPE_LIVE:
                                    liveUrlTemp = fc.getChannelUrl();
                                    break;
                                case NewListAdapter.VIEWTYPE_NEWS:
                                    newsUrlTemp = fc.getChannelUrl();
                                    break;
                                case NewListAdapter.VIEWTYPE_POPULAR:
                                    popularUrlTemp = fc.getChannelUrl();
                                    break;
                                case NewListAdapter.VIEWTYPE_SPECIAL_AREA:
                                    specialAreaUrlTemp = fc.getChannelUrl();
                                    break;
                            }
                        }
                    }

                    getBannerArray(bannerUrlTemp, NewListAdapter.VIEWTYPE_BANNER);


                } else {
                    refreshLayout.refreshComplete();
                }
            }

            @Override
            public void onError(Throwable ex, String errorMsg) {
                super.onError(ex, errorMsg);
                refreshLayout.refreshComplete();
            }

            @Override
            public void onEnd() {
                super.onEnd();
                onNetFinish();
            }


        });
    }


    private synchronized void onNetFinish() {
        if (refreshLayout.isRefreshing()) {
            refreshLayout.refreshComplete();
        }
        if (refreshLayout.isLoading()) {
            refreshLayout.loadMoreComplete();
        }
        refreshLayout.setLoadMoreEnabled(newsIndex + 1 < newsPageAll);
    }

    /**
     * 获取 精选-banner数据
     *
     * @param url
     * @param mode
     * @return
     */
    private boolean getBannerArray(String url, final int mode) {

//        if (!groupOrderHelper.addOne(mode)) {
//            return false;
//        }
        NetUtils.getNetAdapter().getNewsArray(getOwnerName(), url, new AbsListNetCallback<NewsItem>(ListTypeUtils.NewsItem(), mode) {//暂时使用calledIndex来保存mode
            @Override
            public void onSuc(List<NewsItem> newsItems) {
                if (ListUtils.isListValued(newsItems)) {
                    HomeListItem hb = new HomeListItem();
                    hb.setNewsItemList(newsItems);
                    hb.setViewType(NewListAdapter.VIEWTYPE_BANNER);
                    newsList.add(hb);
                    onNetFinish(0);//暂时使用calledIndex来保存mode
                }
            }

            @Override
            public void onEnd() {
                super.onEnd();
                if (!getLiveArray(liveUrlTemp)) {
                }


            }
        });
        return true;
    }


    /**
     * 获取精选--直播数据
     *
     * @param url
     * @return
     */
    private boolean getLiveArray(String url) {

        NetUtils.getNetAdapter().getLiveArray(getOwnerName(), url, new AbsListNetCallback<LiveItem>(ListTypeUtils.LiveItem()) {
            @Override
            public void onSuc(List<LiveItem> liveItems) {

                if (ListUtils.isListValued(liveItems)) {
                    HomeLive hb = new HomeLive();
                    hb.setLiveList(liveItems);
                    hb.setViewType(NewListAdapter.VIEWTYPE_LIVE);
                    newsList.add(hb);
                    onNetFinish(0);//暂时使用calledIndex来保存mode
                }
            }

            @Override
            public void onEnd() {
                super.onEnd();
                if (!getNewsList(NewListAdapter.VIEWTYPE_NEWS, 0)) {
                }
            }
        });
        return true;
    }


    /**
     * 获取 精选--视讯新闻数据
     *
     * @return
     */
    private boolean getNewsList(final int mode, final int index) {

//        if (!groupOrderHelper.addOne(mode)) {
//            return false;
//        }
        NetUtils.getNetAdapter().getNewsPage(getOwnerName(), newsUrlTemp, index, new AbsListNetCallback<NewsItem>(ListTypeUtils.NewsItem()) {
            @Override
            public void onSuc(List<NewsItem> newsItems) {
                newsPageAll = getPageResponse().getData().getPageAll();
                if (ListUtils.isListValued(newsItems)) {
                    newsIndex = index;
                    /***新闻数据请求完成之后获取相应的点击量***/
                    requestNewsClickCount(newsItems);

                }else{
                    onNetFinish(0);//暂时使用calledIndex来保存mode
                }
            }

            @Override
            public void onEnd() {
                super.onEnd();
                if (newsIndex >= newsPageAll - 1) {
                    refreshLayout.setLoadMoreEnabled(false);
                } else {
                    refreshLayout.setLoadMoreEnabled(true);
                }

            }

            @Override
            public List<NewsItem> doInBackground(List<NewsItem> newsItems) {
                return super.doInBackground(newsItems);
            }

            @Override
            public void onError(Throwable ex, String errorMsg, int netCode) {
                super.onError(ex, errorMsg, netCode);
                onNetFinish();
            }
        });
        return true;
    }

    private List<NewsItem> newsItems;

    /**
     * 获取新闻列表点击量
     *
     * @param list
     */
    private void requestNewsClickCount(List<NewsItem> list) {
        if (ListUtils.isListValued(list)) {
            newsItems = new ArrayList<>();
            newsItems.addAll(list);
            List<NewsIdBean> newsIdList = new ArrayList<>();
            NewsIdBean newsBean;
            for (int i = 0; i < list.size(); i++) {
                String type = "10";//默认不返回点击量
                if (list.get(i) instanceof NewsItem) {
                    NewsItem item = (NewsItem) list.get(i);
                    newsBean = new NewsIdBean();
                    newsBean.setId(item.getUrlNewsId());
                    switch (item.getNewsType()) {
                        case Constances.NEWS_TYPE_GRAPHIC:
                        case Constances.NEWS_TYPE_AUDIO:
                        case Constances.NEWS_TYPE_VIDEO:
                            //新闻详情
                            type = "0";
                            break;
                        case Constances.NEWS_TYPE_LIVE:
                            //直播详情
                            type = "1";
                            break;
                        case Constances.NEWS_TYPE_H5:
                            //新闻详情
                            type = "0";
                            newsBean.setId(item.getNewsId());
                            break;
                        default:
                            //其他详情
                            newsBean.setId(item.getNewsId());
                            type = "10";
                            break;
                    }
                    newsBean.setType(type);
                    newsIdList.add(newsBean);
                } else {
                    newsBean = new NewsIdBean();
                    newsBean.setId("1");
                    newsBean.setType(type);
                    newsIdList.add(newsBean);
                }
            }
            if (ListUtils.isListValued(newsIdList)) {
                NewsListClickRequestBean requestBean = new NewsListClickRequestBean();
                requestBean.setNewsIds(newsIdList);
                Gson gson = new Gson();
                String newsId = gson.toJson(requestBean);
                RequestBody body = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), newsId);
                NetUtils.getNetAdapter().getViewsList(getOwnerName(), body, new AbsNetCallBack<NewsListClickVo>(NewsListClickVo.class) {
                    @Override
                    public void onSuc(NewsListClickVo newsListClickVo) {
                        if (null != newsListClickVo && ListUtils.isListValued(newsListClickVo.getResult())) {
                            List<NewsClickCountBean> countList = newsListClickVo.getResult();
                            for (int i = 0; i < countList.size(); i++) {
                                if (newsItems.get(i) instanceof NewsItem&&!TextUtils.isEmpty(countList.get(i).getId())) {
                                    NewsItem item = (NewsItem) newsItems.get(i);
                                    if (item.getNewsType() == Constances.NEWS_TYPE_H5) {
                                        if (countList.get(i).getId().equalsIgnoreCase(item.getNewsId())) {
                                            ((NewsItem) newsItems.get(i)).setReadCount(countList.get(i).getViews());
                                        }
                                    } else if (countList.get(i).getId().equalsIgnoreCase(item.getUrlNewsId())) {
                                        ((NewsItem) newsItems.get(i)).setReadCount(countList.get(i).getViews());
                                    }
                                }
                            }
                        }

                    }

                    @Override
                    public void onEnd() {
                        super.onEnd();
                        if (isRefresh) {
                            isReset = true;
                            newsList.addAll(newsItems);
//                            dataAddHelper.addOrSet24Datass(getContext(), newsList, true);
                            isRefresh = false;
                        } else {
                            newsList.addAll(newsItems);
//                            dataAddHelper.addOrSet24Datass(getContext(), newsItems, false);
                        }
                        onNetFinish(0);//暂时使用calledIndex来保存mode
                    }

                    @Override
                    public void onError(Throwable ex, String errorMsg) {
                        super.onError(ex, errorMsg);
                    }
                });
            }
        }
    }

    private void resetUrlTemps() {
        bannerUrlTemp = null;
    }

    private synchronized void onNetFinish(int mode) {
        refreshLayout.refreshComplete();
        refreshLayout.loadMoreComplete();
        if (adapter == null) {
            adapter = new NewListAdapter(this, newsList);//dataAddHelper.getAdapter(getContext());
            ArrayList<Pair<String, String>> pairs = new ArrayList<>();
            pairs.add(new Pair<>("页面", "首页"));
            pairs.add(new Pair<>("栏目", "精选"));
//            pairs.add(new Pair<>("行为类型", "点击"));
            adapter.setActivity(this);
            adapter.setPairs(pairs);
            recyclerView.setAdapter(adapter);
        } else {
            adapter.setDatass(newsList);
        }
        if (isReset) {
            isReset = false;
            handler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    recyclerView.smoothScrollToPosition(0);
////                    recyclerView.scrollTo(0,0);
//                    layoutManager.scrollToPositionWithOffset(0,0);
                }
            }, 700);
        }
    }



    /**
     * 增加直播点击
     *
     * @param liveID
     */
    private void initViewClickData(final String liveID) {
        ArrayMap<String, Object> p = new ArrayMap<>();
        p.put("id", liveID);
        p.put("type", 1);//type（0.新闻 1.直播)
        NetUtils.getNetAdapter().addNewOrLivingClick(getOwnerName(), p, new AbsNetCallBack<SingleResult>(SingleResult.class) {
            @Override
            public void onSuc(SingleResult vo) {
                JLog.e("initViewClickData", "GreatestFragment liveID = " + liveID + vo.isSuccess());
            }

            @Override
            public void onEnd() {
                super.onEnd();
            }

            @Override
            public void onError(Throwable ex, String errorMsg) {
                super.onError(ex, errorMsg);
            }
        });


    }


}
